import echarts from 'echarts'
// import echarts from "echarts-gl"
// import * as esriLoader from 'esri-loader';
import { graphic, init, matrix, registerCoordinateSystem } from 'echarts'
// import MapTools from '@/utils/arcgisapi'
import { loadEsriModule } from '@/utils/jsapi'
import env from '@/utils/env'
import store from '@/vuex/store'
import bus from '@/modules/eventbus'
//  export const echartsLayer= {}
// var graphic = echarts.graphic,
// init = echarts.init,
// matrix = echarts.matrix,
// registerCoordinateSystem = echarts.registerCoordinateSystem;

async function ChartLayer (view, option) {
  const [Map, MapView, MapImageLayer, Point, IdentifyTask, IdentifyParameters, GeoJSONLayer, SpatialReference] = await loadEsriModule([
    'esri/Map',
    'esri/views/MapView',
    'esri/layers/MapImageLayer',
    'esri/geometry/Point',
    'esri/tasks/IdentifyTask',
    'esri/tasks/support/IdentifyParameters',
    'esri/layers/GeoJSONLayer',
    'esri/geometry/SpatialReference'
  ])
  var newMap = new Map({
    layers: []
  })

  var newView = new MapView({
    container: view.container,
    map: newMap,
    extent: {
      // xmax: 13195421.283757377,
      // xmin: 12840863.397774596,
      // ymax: 5106612.0524428375,
      // ymin: 4744998.335427837,
      xmax: 13332182.218845742,
      xmin: 12712103.47868826,
      ymax: 5069823.481971914,
      ymin: 4783787.15989927,
      spatialReference: { wkid: 102100 }
    },
    // scale: 1400000,
    // extent: {
    //     xmin: 12848154.905691,
    //     ymin: 4758043.595465,
    //     xmax: 13080960.893842,
    //     ymax: 4993011.825674,
    //     spatialReference:  {wkid: 102100},
    // },
    constraints: {
      rotationEnabled: false
    },
    spatialReference: { wkid: 102100 },
    ui: {
      components: []
    }

  })
  var layer_region = new MapImageLayer({
    url: env.getDefaultVectorMap(),
    sublayers: env.getVectorSubLayers()
  })

  newMap.add(layer_region)
  rendererRegion()
  registerCoordinateSystem('arcgis', getE3CoordinateSystem(newView))
  /* 自定义layer对象 */
  var layer = {
    view: null,
    box: null,
    chart: null,
    chartOption: null,
    visible: true,
    init (view, option) {
      let self = this
      view.when(function () {
        self.setBaseMap(view)
        self.setChartOption(option)
        createLayer()
      })
    },
    setBaseMap (view) {
      this.view = view
    },
    setChartOption (option) {
      this.chartOption = option
      // setCharts();
    },
    setVisible (bool) {
      if (!this.box || this.visible === bool) return
      this.box.hidden = !bool
      this.visible = bool
      bool === true && setCharts()
    },
    refreshBegin () {
      this.box.hidden = true
    },
    refreshing () {
      setCharts()
    },
    refreshEnd () {
      this.box.hidden = false
    },
    map_DragStart_Listener: null,
    map_DragEnd_Listener: null,
    map_ZoomStart_Listener: null,
    map_ZoomEnd_Listener: null,
    map_ExtentChange_Listener: null,
    map_click_Listener: null
  }

  layer.init(newView, option)
  this.setChartOption = function (option) {
    rendererRegion()
    layer.setChartOption(option)
    setCharts()
    highlightFeature(layer.view, store.getters.curfeature)
  }
  this.setVisible = function (bool) {
    layer.setVisible(bool)
  }
  this.remove = function () {
    removeLayer()
  }
  this.removeHtml = function () {
    removeHtml()
  }
  this.on = function (eventName, handler, context) {
    layer.chart.on(eventName, handler, context)
  }
  this.off = function (eventName, handler, context) {
    layer.chart.off(eventName, handler, context)
  }
  this.getChartOption = function () {
    return layer.chartOption
  },
  this.getChart = function () {
    return layer.chart
  }
  this.getMapView = function () {
    return layer.view
  }
  this.queryFeatures = function (regionCode) {
    return queryFeatures(regionCode)
  }
  // this.highlightFeature = function(view, feature){
  //     highlightFeature(view, feature)
  // }

  function rendererRegion () {
    var layer_qx = layer_region.findSublayerById(1)
    layer_qx.labelingInfo[0].labelExpression = '[name]' // '"beijing" CONCAT [name]';//
    layer_qx.labelingInfo[0].symbol = {
      type: 'text',
      color: '#a6c84c',
      font: {
        family: 'Microsoft YaHei',
        size: 14
      }
    },
    layer_qx.labelsVisible = true
    layer_qx.renderer = {
      type: 'simple',
      symbol: {
        type: 'simple-fill',
        color: [19, 41, 55, 0.5],
        outline: {
          width: 0.5,
          color: '#0692a4'
        }
      }
    }
  }
  /* 绘制echarts */
  function setCharts () {
    if (!layer.visible) return
    let baseMap = layer.view
    let baseExtent = baseMap.extent
    // 判断是否使用了mark类型标签，每次重绘要重新转换地理坐标到屏幕坐标
    // 根据地图extent,重绘echarts
    layer.chartOption.xAxis = { show: false, min: baseExtent.xmin, max: baseExtent.xmax }
    layer.chartOption.yAxis = { show: false, min: baseExtent.ymin, max: baseExtent.ymax }
    // layer.chart.setOption(layer.chartOption)
    setTimeout(layer.chart.setOption(layer.chartOption, true), 1000)
    layer.chartOption.animation = false
  };
  /* 创建layer的容器，添加到map的layers下面 */
  function createLayer () {
    let box = layer.box = document.createElement('div')
    box.setAttribute('id', 'testData')
    box.setAttribute('name', 'testData')
    box.style.width = view.width + 'px'
    box.style.height = view.height + 'px'
    box.style.position = 'absolute'
    box.style.top = 0
    box.style.left = 0
    let parent = document.getElementsByClassName('esri-view-surface')[0]
    // console.log(parent, '6666666666')
    parent.appendChild(box)
    layer.chart = echarts.init(box)
    setCharts()
    // console.log(store.getters)
    // highlightFeature(layer.view,store.getters.curfeature)
    startMapEventListeners()
  };
  /* 销毁实例 */
  function removeLayer () {
    if (layer.view) {
      // layer.view.graphics.removeAll()// 清除上一次点击目标
      layer.box.outerHTML = ''
      layer.view = null
      layer.box = null
      layer.originLyr = null
      layer.features = null
      layer.screenData = []
      layer.chart = null
      layer.chartOption = null
      // layer.map_DragStart_Listener.remove();
      // layer.map_DragEnd_Listener.remove();
      // layer.map_ZoomStart_Listener.remove();
      // layer.map_ZoomEnd_Listener.remove();
      layer.map_ExtentChange_Listener.remove()
    }
    // layer.map_click_Listener.remove();
  };
  function removeHtml () {
    if (layer.view) {
      // layer.view.graphics.removeAll()// 清除上一次点击目标
      layer.box.outerHTML = ''
      // layer.map_ExtentChange_Listener.remove();
    }
    // layer.map_click_Listener.remove();
  };
  /* 监听地图事件，根据图层是否显示，判断是否重绘echarts */
  function startMapEventListeners () {
    let view = layer.view

    let layer_qx = layer_region.findSublayerById(1)
    layer_qx.popupEnabled = false

    layer.map_ExtentChange_Listener = view.watch('extent', function (event) {
      if (!layer.visible) return
      setCharts()
      layer.chart.resize()
      layer.box.hidden = false
      // console.log(view)
    })
    layer.map_click_Listener = view.on('click', executeIdentifyTask)
    // layer.map_ExtentChange_Listener = view.watch("rotation",function () {
    //     if(!layer.visible) return;
    //     setCharts();
    //     layer.chart.resize();
    //     layer.box.hidden = false;
    // });
  }
  function queryFeatures (regionCode) {
    // 1、查找图层
    var layer = newView.map.allLayers.getItemAt(0)

    var layer1 = layer.findSublayerById(1)
    // 2、查找Feature
    let query = layer1.createQuery()
    query.where = "code = '" + regionCode + "'"
    return layer1.queryFeatures(query)
  }
  function highlightFeature (view, feature) {
    let mapView = view || newView
    view.graphics.removeAll()// 清除上一次点击目标
    if (feature) {
      let graphic = feature
      graphic.symbol = {
        type: 'simple-fill',
        // color: [127,255,0,0.3],
        color: [11, 28, 45, 1],
        outline: {
          type: 'simple-line',
          //  color: [127,255,0,1],//[176, 255, 255, 1],
          color: '#0692a4',
          width: 1.5,
          style: 'solid'
        }
      }
      mapView.graphics.add(graphic)// 添加新的点击目标
    }
  }
  function executeIdentifyTask (event) {
    var identifyTask, params
    // console.log(env.getDefaultVectorMap())
    identifyTask = new IdentifyTask(env.getDefaultVectorMap())

    // Set the parameters for the Identify
    params = new IdentifyParameters()
    params.tolerance = 3
    params.layerIds = [1]
    params.layerOption = 'top'
    params.width = newView.width
    params.height = newView.height
    params.returnGeometry = true
    newView.graphics.removeAll()// 清除上一次点击目标
    newView.popup.visible = false
    params.geometry = event.mapPoint
    params.mapExtent = newView.extent
    identifyTask
      .execute(params)
      .then(function (response) {
        var results = response.results[0]
        let graphic = results.feature
        let regionCode = results.feature.attributes['code']
        let regionName = results.feature.attributes['name'].replace('区', '').replace('乡', '').replace('镇', '').replace('街道', '').replace('地区', '')
        highlightFeature(newView, graphic)
        bus.$emit('drillDownName', { regioncode: regionCode, regionname: regionName })
        store.dispatch('changeIsMapClick', true)
        store.dispatch('changefeature', graphic)
      })
  }
  // /*监听图层的transform*/
  // function mapTransformWatcher(target,config) {
  // 	let MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
  // 	let observer = new MutationObserver(function(mutations) {
  // 		mutations.some(mutation=>{
  // 			let isTransform = ( mutation.attributeName === "style" );
  // 			isTransform && ( layer.box.style.transform = mutation.target.style.transform );
  // 			return isTransform;
  // 		})
  // 	});
  // 	observer.observe(target, config);
  // 	return observer;
  // }
  // /*重置layer的transform*/
  // function layerTransformReset() {
  // 	layer.box.style.transform = "";
  // }
  function getE3CoordinateSystem (map) {
    var CoordSystem = function CoordSystem (map) {
      this.map = map
      this._mapOffset = [0, 0]
    }
    CoordSystem.create = function (ecModel) {
      ecModel.eachSeries(function (seriesModel) {
        if (seriesModel.get('coordinateSystem') === 'arcgis') {
          seriesModel.coordinateSystem = new CoordSystem(map)
        }
      })
    }
    CoordSystem.getDimensionsInfo = function () {
      return ['x', 'y']
    }
    CoordSystem.dimensions = ['x', 'y']
    CoordSystem.prototype.dimensions = ['x', 'y']
    CoordSystem.prototype.setMapOffset = function setMapOffset (mapOffset) {
      this._mapOffset = mapOffset
    }
    CoordSystem.prototype.dataToPoint = function dataToPoint (data) {
      var point = new Point({
        type: 'point',
        x: data[0],
        y: data[1],
        spatialReference: { wkid: 102100 }
      })
      var px = map.toScreen(point)
      var mapOffset = this._mapOffset
      return [px.x - mapOffset[0], px.y - mapOffset[1]]
    }
    CoordSystem.prototype.pointToData = function pointToData (pt) {
      var mapOffset = this._mapOffset
      var screentPoint = { x: pt[0] + mapOffset[0],
        y: pt[1] + mapOffset[1]
      }
      var data = map.toMap(screentPoint)
      return [data.x, data.y]
    }
    CoordSystem.prototype.getViewRect = function getViewRect () {
      return new graphic.BoundingRect(0, 0, this.map.width, this.map.height)
    }
    CoordSystem.prototype.getRoamTransform = function getRoamTransform () {
      return matrix.create()
    }
    return CoordSystem
  }
  //  return layer;
  return this
};

export default ChartLayer
